package abc.red.controller;

import abc.red.common.BaseContext;
import abc.red.entity.R;
import abc.red.entity.Manager;
import abc.red.tools.StringTool;
import abc.red.service.ManagerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName LoginController
 * @Author YiXia
 * @Date 2024/1/12 11:48
 * @Version 1.0
 * @Description TODO
 **/


@Slf4j
@RestController
@RequestMapping("/red")
public class LoginOutController {

    private static final StringTool TOOL =new StringTool();

    @Autowired
    private ManagerService service;




    /**登录*/
    @PostMapping("/login")
    @CrossOrigin
    public R<Manager> login(HttpServletRequest request, @RequestBody Manager m){

        //打印session的信息


//        log.info("loginSession={}",request.getSession());


        //数据校验
        if(!TOOL.fun1(m.getName()) || !TOOL.fun1(m.getPassword())){
            return R.error("数据不合法,请检查后重新输入");
        }

        //信息加密
        String md5Password = DigestUtils.md5DigestAsHex(m.getPassword().getBytes());


        //查询sql
        LambdaQueryWrapper<Manager> qw=new LambdaQueryWrapper<Manager>();
        qw.eq(Manager::getName,m.getName());
        Manager sqlm=service.getOne(qw);


        //找不到数据
        if(sqlm==null){
            return R.error("用户名错误，请检查后重新输入");
        }


        //密码比对
        if(!sqlm.getPassword().equals(md5Password)){
            return R.error("密码错误，请检查后重新输入");
        }


        //查看员工状态
        if(sqlm.getStatus()==0){
            return R.error("账号已禁用");
        }


        //可以登录了
        request.getSession().setAttribute("manager",sqlm.getId());
        System.out.println("登陆id=  "+sqlm.getId());
        return R.success(sqlm);
    }


    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        System.out.println("登出的id=  "+ BaseContext.getCurrentId());
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }


}
